package com.yuoj.yuojbackendjudgeservice.strategy;

import cn.hutool.json.JSONUtil;
import com.yuoj.backendcommon.codesandbox.JudgeInfo;
import com.yuoj.backendcommon.dto.question.JudgeCase;
import com.yuoj.backendcommon.dto.question.JudgeConfig;
import com.yuoj.backendcommon.entity.Question;
import com.yuoj.backendcommon.enums.JudgeInfoMessageEnum;
import com.yuoj.yuojbackendjudgeservice.JudgeContext;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 刘渠好
 * @since 2025-04-05 13:16
 * java程序策略
 */
public class JavaStrategy implements JudgeStrategy {
    @Override
    public JudgeInfo doJudge(JudgeContext context) {
        Question question = context.getQuestion ();
        List<String> outputList = context.getOutputList ();
        JudgeInfo info = context.getJudgeInfo ();
        Long time = Optional.ofNullable (info.getTime ()).orElse (0L);
        Long memory = Optional.ofNullable (info.getMemory ()).orElse (0L);

        JudgeInfo judgeInfo = new JudgeInfo ();
        judgeInfo.setMessage (JudgeInfoMessageEnum.ACCEPT.getText ());
        judgeInfo.setMemory (memory);
        judgeInfo.setTime (time);

        //判断题目的输出用例是否一致
        String judgeCase = question.getJudgeCase ();
        List<JudgeCase> judgeCases = JSONUtil.toList (judgeCase, JudgeCase.class);
        List<String> collect = judgeCases.stream ().map (JudgeCase::getOutput).collect (Collectors.toList ());
        //判断数量是否一致
        if (collect.size ()!=outputList.size ()) {
            judgeInfo.setMessage (JudgeInfoMessageEnum.WRONG_ANSWER.getText ());
            return judgeInfo;
        }
        //判断具体的数据是否一致
        for (int i = 0; i < collect.size (); i++) {
            if (!collect.get (i).equals (outputList.get (i))) {
                judgeInfo.setMessage (JudgeInfoMessageEnum.WRONG_ANSWER.getText ());
                return judgeInfo;
            }
        }

        //判断时间 内存是否在规定范围内
        String judgeConfig = question.getJudgeConfig ();
        JudgeConfig config = JSONUtil.toBean (judgeConfig, JudgeConfig.class);
        Long timeLimit = config.getTimeLimit ();
        Long memoryLimit = config.getMemoryLimit ();
        //java程序时间延长10s
        if (time> (timeLimit+10)) {
            judgeInfo.setMessage (JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED.getText ());
            return judgeInfo;
        }
        if (memory > memoryLimit) {
            judgeInfo.setMessage (JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED.getText ());
            return judgeInfo;
        }
        return judgeInfo;
    }
}
